(function(namespace){
	"use strict";	
	var bodyDiv_desktop = "bodyDiv_desktop",
		topDiv_desktop = "topDiv_desktop",
		bottom_desktop = "bottomDiv_desktop",
		areaDiv_desktop = "areaDiv_desktop",
		item_body_desktop = "item_body_desktop",
		item_img_desktop = "item_img_desktop",
		item_name_desktop ="item_name_desktop";
		
	var item_height = 74, item_width = 60;
	var rowcount = null,colcount= null,rowgap = null,colgap = null;
	var cells = {};

	DeskTop.allType = "all",DeskTop.fileType = "file",DeskTop.systemType ="system";
	
	function DeskTop (options){
		this.options = options || {};
		var options = this.options;
		this.wnd = options["window"] || window;
		this.doc = options["docuement"] || window.document;
		this.parentDom = options["parentDom"] || this.doc.body;
		this.items = [];
		this.selectedItems = [];
		this.autoAlign =  true;
		_initUI.call(this);
		_initEvents.call(this);
		_initDeskTopGrid.call(this);
	}
	
	function _initUI(){
		this.bodyDiv = $("<div>").addClass(bodyDiv_desktop).appendTo(this.parentDom);
		this.topDiv = $("<div>").addClass(topDiv_desktop).appendTo(this.bodyDiv);
		this.bottomDiv = $("<div>").addClass(bottom_desktop).appendTo(this.bodyDiv);
		this.areaDiv = $("<div>").addClass(areaDiv_desktop).appendTo(this.topDiv);
		_resizeEvents.call(this);
	}
	
	/**
	 * 初始化格子
	 */
	function _initDeskTopGrid(){
		var allwidth = this.topDiv.width();
		var allheight = this.topDiv.height();
		rowcount = Math.floor(allheight/(item_height+(6*2)));
		colcount = Math.floor(allwidth/(item_width+(6*2)));
		rowgap = allheight/rowcount;
		colgap = allwidth/colcount;
	}
	
	/**
	 * 找出格子算法  
	 * yes说明如果没有找到将自己根据算法找个
	 */
	function cell(row,col,yes){
		if (col < 0) col = 0;
		if (col >colcount-1) col = colcount -1;
		if (row < 0) row = 0;
		if (row > rowcount-1) row = rowcount-1;
		var flag = cells[row+""+col];
		if (flag) {
			if (yes) {
				for(var sign = false;col<colcount;){
					for(;row<rowcount;){
						if(!cells[row+""+col]){
							//row = i;
							//col = j;
							sign=true;
							break;
						}
						row++;
					}
					if(sign)break;
					col++;
					row = 0;
				}
			} else {
				return false;
			}
		}
		var x = row *rowgap;
		var y = col *colgap;
		return [y+10,x+10,row,col];
	}
	
	/**
	 * 整理位置
	 */
	function fixItemsPosition(item){
		if(!this.autoAlign)return;
		if(item instanceof FileItem){
			item.setPosition(item.position.left,item.position.top);
		}else{
		for(var i=0,len = this.items.length;i<len;i++){
			var item = this.items[i];
			fixItemsPosition.call(this,item);
		}
		}
	}
	/**
	 * 大小变动事件
	 */
	function _resizeEvents(){
		var topHeight = this.bodyDiv.height()-40-1;
		this.topDiv.height(topHeight);
	}
	
	/**
	 * 空白区域的click事件
	 */
	function on_click_event(){
		if(this.areaSelected){
			this.areaSelected=false;
		}else{
			this.clearSelectedItems();
		}
	}
	
	/**
	 * 空白mousedown事件
	 */
	function on_mouse_down_event(evt){
		var fromObj = {left:evt.pageX,top:evt.pageY};
		this.topDiv.bind("mousemove.move",{fromObj:fromObj},on_mouse_move_event.bind(this));
		this.topDiv.bind("mouseup.move",{fromObj:fromObj},on_mouse_up_event.bind(this));
	}
	/**
	 * 鼠标移动事件
	 */
	function on_mouse_move_event(evt){
		evt.preventDefault();
		var x = evt.pageX;
		var y = evt.pageY;
		var fromObj = evt.data.fromObj;
		var bottomDivOffset = fromObj.bottomDivOffset;
		if(bottomDivOffset){
			if(y>=bottomDivOffset.top-1){
				itemCloneDispose.call(this);
				this.topDiv.unbind(".move .moveitem");
				return;
			}
		}
		var absX = Math.abs(fromObj.left-x);
		var absY = Math.abs(fromObj.top-y);
		if(absX<=2&&absY<=2)return;
		if(fromObj.obj){
			item_mouse_move.call(this,evt,fromObj.obj);
		}else{
			areaDiv_move_event.call(this,evt);
		}
	}
	
	/**
	 * 当初边界的时候释放克隆对象
	 */
	function itemCloneDispose(){
		for(var i =0,len = this.selectedItems.length;i<len;i++){
			var item =  this.selectedItems[i];
			if(item._clone){
				var clone =item._clone;
				clone.remove();
				item._clone = null;
			}
		}
		this.topDiv.unbind(".moveitem  .move");
	}
	/**
	 * 鼠标松开事件  
	 * ###！！！这里出现了一个问题 就是areaDiv一定要在topDiv里面 不然mouseup事件无法触发
	 */
	function on_mouse_up_event(evt){
		item_mouse_up.call(this,evt);
		this.areaDiv.css("display","none");
		this.topDiv.unbind(".moveitem  .move");
	}
	
	/**
	 * topDiv右键菜单
	 */
	function on_top_context_menu_event(evt){
		if(typeof this.topcontextmenu == "function") this.topcontextmenu(evt,this);
		return false;
	}
	/**
	 * bottomDiv右键菜单
	 */
	function on_bottom_context_menu_event(evt){
		if(typeof this.bottomcontextmenu == "function") this.bottomcontextmenu(evt,this);
		return false;
	}
	/**
	 * 初始化事件
	 */
	function _initEvents(){
		$(window).bind("resize", _resizeEvents.bind(this));
		$(this.bodyDiv).bind({
			"contextmenu.desktop" : function() {
				return false;
			}
		});
		$(this.topDiv).bind({
			"mousedown.desktop" : on_mouse_down_event.bind(this),
			"click.desktop" : on_click_event.bind(this),
			"contextmenu" : on_top_context_menu_event.bind(this)
		});
		$(this.bottomDiv).bind({
			"contextmenu" : on_bottom_context_menu_event.bind(this),
			"mousemove" : function(){return false;},
			"mouseover" : function(){
				itemCloneDispose.call(this);
			}.bind(this)
			});
	}
	
	/**
	 * 计算距离
	 */
	function item_distance(obj,src){
		var objoffset = obj.bodyDiv.offset();
		var srcoffset = src.bodyDiv.offset();
		var arr=[];
		arr.push(srcoffset.left-objoffset.left,srcoffset.top-objoffset.top);
		return arr;
	}
	
	
	/**
	 * 拖动item的事件
	 */
	function item_mouse_move(evt,fromObj){
		if (!fromObj)
			return;
		var selectedItems = this.selectedItems;
		if(!selectedItems.length) selectedItems.push(fromObj);
		var len = selectedItems.length;
		var types = [];
		var x = evt.pageX;
		var y = evt.pageY;
		for ( var i = 0; i < len; i++) {
			var item = this.selectedItems[i];
			types.push(item.type);
			var arr = item_distance(item,fromObj);
			if (!item._clone) {
				var cloneDom = item.bodyDiv.clone(false);
				cloneDom.css({
					"position" : "absolute",
					background : ""
				});
				$(item.owner.topDiv).append(cloneDom);
				item._clone = cloneDom;
				if(len > 1){
					delete cells[item._oripos];
				}
			}
			item._clone.css({
				left : x - 50-arr[0],
				top : y - 50-arr[1],
				opacity : 0.5
			});
		}
		var lastTargetItem = this.targetItem;
		var flag = selectedItems.indexOf(lastTargetItem) ==-1;
		if (lastTargetItem && flag) {
			lastTargetItem.bodyDiv.css("background", "");
		}
		lastTargetItem = this.targetItem = findItemByPosition.call(this,x, y);
		if (lastTargetItem && flag)
			lastTargetItem.bodyDiv.css("background", "rgb(154,208,244)");
	}
	
	/**
	 * 鼠标松开后 item处理的逻辑
	 */
	function item_mouse_up(evt){
		var len = this.selectedItems.length;
		if(len>1) var yes = true;
		for ( var i = 0; i < len; i++) {
			var item = this.selectedItems[i];
			if (item._clone) {
				var clone = item._clone;
				if(this.targetItem){
					item.moveIntoDir(this.targetItem);
				}else{
				var offset = $(clone).offset();
				item.setPosition(offset.left,offset.top,yes);
				}
				clone.remove();
				item._clone = null;
			}
		}
	}

	/**
	 * 根据区域找item 框选div用的
	 */
	function findItemByArea(left,top){
		var items = this.items;
		var areawidth = this.areaDiv.width();
		var areaheight = this.areaDiv.height();
		var offset = this.areaDiv.offset();
		var left =offset.left,top = offset.top;
		for(var i =0 ,len=items.length;i<len;i++){
			var item = items[i];
			var width = item.bodyDiv.width();
			var height = item.bodyDiv.height();
			var position = item.position;
			if((left<=(position.left+30)&&(position.left+width-30)<=(left+areawidth))&&(top<=position.top+50&&(position.top+height-50)<=(top+areaheight))){
				item.setSelected(true);
				this.areaSelected = true;
			}else{
				item.setSelected(false);
			}
				
		}
	}

	/**
	 * 根据位置找 item 总感觉遍历的办法太傻了。。
	 * @param x
	 * @param y
	 * @returns {*}
	 */
	function findItemByPosition(x,y){
		var items = this.items;
		for (var i = 0, len = items.length; i < len; i++) {
			var item = items[i];
			var position = item.position;
			var left = position.left,top = position.top;
			if(numberBetween(x,left,(left+item_width))&&numberBetween(y,top,(top+item_height))){
				return item ;
			}
		}
	}

	/**
	 * @param m 目标数字
	 * @param x 范围 小者
	 * @param y 范围 大者
	 * @returns {boolean}
	 */
	function numberBetween(m,x,y){
		if(m>=x&&y>=m) return true;
		return false;
	}
	/**
	 * div移动事件
	 */
	function areaDiv_move_event(evt){
		var x = evt.pageX;
		var y = evt.pageY;
		var fromObj = evt.data.fromObj;
		var fromx = fromObj.left;
		var fromy = fromObj.top;
		this.areaDiv.css({
			display:"block",
			left:Math.min(fromx,x),
			top:Math.min(fromy,y),
			width:Math.abs(x-fromx)+"px",
			height:Math.abs(y-fromy)+"px"
		});
		findItemByArea.call(this,Math.min(fromx,x),Math.min(fromy,y));
	}
	/**
	 * 增加
	 * @param options
	 */
	DeskTop.prototype.addItem = function(options){
		var item = new FileItem(options,this);
		this.items.push(item);
	};
	
	/**
	 * 清除所以选中
	 */
	DeskTop.prototype.clearSelectedItems = function(){
		while(this.selectedItems.length){
			this.selectedItems[this.selectedItems.length-1].setSelected(false);
		}
	};
	/**
	 * 设置桌面右键事件
	 * @param func
	 */
	DeskTop.prototype.setOnTopContextMenu = function(func){
		this.topcontextmenu = func;
	};
	
	/**
	 * 设置底部的右键菜单
	 * @param func
	 */
	DeskTop.prototype.setOnBottomContextMenu = function(func){
		this.bottomcontextmenu = func;
	};
	/**
	 * 设置定位方位
	 * @param yes
	 */
	DeskTop.prototype.setPositionMode = function(yes){
		this.autoAlign = yes;
		if(this.autoAlign){
			cells = {};
			fixItemsPosition.call(this);
		}
	};
	
	function FileItem(options,owner){
		this.options = options || {};
		var options = this.options;
		this.owner = owner;
		this.parent = this.owner.topDiv;
		this.highlight = false;
		this.position ={
				left:options["left"],
				top:options["top"]
		};
		this.fileType = options["type"];
		_initItemUI.call(this);
		_initItemEvents.call(this);
	}
	
	function _initItemUI(){
		var options = this.options;
		this.bodyDiv = $("<div>").addClass(item_body_desktop).appendTo(this.parent);
		this.bodyDiv._sancomponent = this;
//		this.bodyDiv.css({top:this.position["top"],left:this.position["left"]});
		this.img = $("<img>").attr("src",options["img"]).addClass(item_img_desktop).appendTo(this.bodyDiv);
		this.nameDiv = $("<div>").addClass(item_name_desktop).text(options["name"]).appendTo(this.bodyDiv);
		this.setPosition(this.position["top"],this.position["left"],true);
	}
	
	function _initItemEvents(){
		var self = this;
		this.bodyDiv.bind({
			click:item_on_click_event.bind(this),
			mousedown:item_on_mouse_down_event.bind(this)});
	}
	
	function item_on_click_event(evt){
		evt.stopPropagation();
		if(evt.ctrlKey){
			this.setSelected(!this.highlight);
			
		}else{
			this.owner.clearSelectedItems();
			this.setSelected(true);
		}
	}
	
	/**
	 * 在item mousedown
	 */
	function item_on_mouse_down_event(evt){
		evt.stopPropagation();
		if(evt.ctrlKey){
			
		}else{
		if(this.highlight==false){
			this.owner.clearSelectedItems();
			this.setSelected(true);
		}else{
//			this.bodyDiv.css("background","rgb(154,208,244)");
		}
		}
		var owner =this.owner;
		var bottomDivOffset = $(this.owner.bottomDiv).offset();
		var fromObj = {left:evt.pageX,top:evt.pageY,obj:this,bottomDivOffset:bottomDivOffset};
		//this.owner.bodyDiv.bind("mousemove",{fromObj:fromObj},on_mouse_move_event.bind(this));
		this.owner.topDiv.bind("mousemove.moveitem",{fromObj:fromObj},on_mouse_move_event.bind(owner));
		this.owner.topDiv.bind("mouseup.moveitem",on_mouse_up_event.bind(this.owner));
		this.owner.topDiv.bind("mouselout.move",function(){
			for(var i =0,len = this.selectedItems;i<len;i++){
				var item =  this.selectedItems[i];
				console.log(item);
				if(item._clone){
					var clone =item._clone;
					clone.remove();
					item._clone = null;
				}
			}
		}.bind(this));
	}
	

	
	FileItem.prototype.setSelected = function(yes,evt){
		var index = this.owner.selectedItems.indexOf(this);
		if(yes){
			this.bodyDiv.css("background","rgb(154,208,244)");
			this.highlight = true;
			if(index ==-1){
				this.owner.selectedItems.push(this);
			}
		}else{
			this.bodyDiv.css("background","");
			this.highlight = false;
			if(index !=-1){
				this.owner.selectedItems.splice(index,1);
			}
		}
	};
	
	/**
	 * 设置位置
	 * @param left
	 * @param top
	 * @yes 在自动对齐的情况下如果有位置了将会从头开始找个最近空的位置
	 */
	FileItem.prototype.setPosition = function(left,top,yes){
		var arr = [];
		if(this.owner.autoAlign){
		var colnum = Math.round(left/ colgap);
		var rownum = Math.round(top/ rowgap);
		arr = cell(rownum, colnum,yes);
		if(!arr) return false;
		rownum = arr[2];
		colnum = arr[3];
		var oripos = this._oripos;
		if (oripos){
			delete cells[oripos];
		}
		var curpos = rownum + "" + colnum;
		cells[curpos] = this;
		this._oripos = curpos;
		}else{
			arr[0]=left;
			arr[1]=top;
		}
		this.bodyDiv.css({
			left : arr[0],
			top : arr[1]
		});
		this.position = {
			left : arr[0],
			top : arr[1]
		};
	};

	FileItem.prototype.moveIntoDir = function(desDirItem){
		if(desDirItem.droptype){
			if(desDirItem.droptype == DeskTop.allType || desDirItem.droptype == this.fileType) {

			}


		}
	}
	
	namespace["DeskTop"] = DeskTop;
})(window);